﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

/// <summary>
///SharpZipLibHelper 的摘要说明
/// </summary>
public class SharpZipLibHelper
{
    List<string> files = new List<string>();    //all files
    List<string> emptyFolders = new List<string>();    //all empty folders

    /// <summary>
    /// Compress the file or folder
    /// </summary>
    /// <param name="source">source file or folder path</param>
    /// <param name="isFolder">whether the source is folder</param>
    /// <param name="targetFile">target file path</param>
    public void ZipFileOrFolder(string sourcePath, bool isFolder, string targetFile)
    {
        if (isFolder)
        {
            ZipFolder(sourcePath, targetFile);
        }
        else
        {
            ZipSingleFile(sourcePath, targetFile);
        }
    }

    /// <summary>
    /// Zip files
    /// </summary>
    /// <param name="sourceFilelist">the list of file info,filename with extension and content</param>
    /// <returns></returns>
    public byte[] ZipFile(List<FileToZipArgument> sourceFilelist)
    {
        MemoryStream ms = new MemoryStream();
        Crc32 crc = new Crc32();
        using (ZipOutputStream zipStream = new ZipOutputStream(ms))
        {
            zipStream.SetLevel(9);
            sourceFilelist.ForEach(p =>{
                ZipEntry entry = new ZipEntry(p.FileName);
                entry.DateTime = DateTime.Now;
                entry.Size = p.FileContent.Length;
                crc.Reset();
                crc.Update(p.FileContent);
                entry.Crc = crc.Value;
                zipStream.PutNextEntry(entry);
                zipStream.Write(p.FileContent, 0, p.FileContent.Length);
            });
            zipStream.Finish();
        }
        return ms.ToArray();
    }
    
    /// <summary>
    /// zip single files
    /// </summary>
    /// <param name="fileName">file name with extension</param>
    /// <param name="content">file content</param>
    /// <returns></returns>
    public byte[] ZipFile(string fileName, byte[] content)
    {
        List<FileToZipArgument> list = new List<FileToZipArgument>();
        list.Add(new FileToZipArgument { FileName = fileName, FileContent = content });
        return ZipFile(list);
    }
    
    /// <summary>
    /// Uncompress the zipped file
    /// </summary>
    /// <param name="zippedFile">zipped file path</param>
    /// <param name="targetDirectory">target directory</param>
    public void UnZip(string fileToUnZip, string unZipDestinationDirectory)
    {
        if (!unZipDestinationDirectory.EndsWith("\\"))
        {
            unZipDestinationDirectory += "\\";
        }
        ZipInputStream inputStream = new ZipInputStream(File.OpenRead(fileToUnZip));
        ZipEntry theEntry;        
        while ((theEntry = inputStream.GetNextEntry()) != null)
        {
            if (theEntry.Name != String.Empty)
            {
                string path = unZipDestinationDirectory + theEntry.Name;
                Directory.CreateDirectory(Path.GetDirectoryName(path));
                if (path.EndsWith("\\")) continue;
                FileStream streamWriter = File.Create(path);
                int size = 2048;
                byte[] data = new byte[2048];
                while (true)
                {
                    size = inputStream.Read(data, 0, data.Length);
                    if (size > 0)
                    {
                        streamWriter.Write(data, 0, size);
                    }
                    else
                    {
                        break;
                    }
                }
                streamWriter.Close();
            }
        }
        inputStream.Close();
    }
    
    private void ZipSingleFile(string source, string targetFile)
    {
        if (!System.IO.File.Exists(source))
        {
            throw new FileNotFoundException("The specified file " + source + " could not be found.");
        }

        FileStream streamToZip = new FileStream(source, FileMode.Open, FileAccess.Read);
        FileStream zipFile = File.Create(targetFile);
        ZipOutputStream zipStream = new ZipOutputStream(zipFile);
        ZipEntry zipEntry = new ZipEntry(Path.GetFileName(source));
        zipStream.PutNextEntry(zipEntry);
        zipStream.SetLevel(9);
        byte[] buffer = new byte[4096];
        int size = streamToZip.Read(buffer, 0, buffer.Length);
        zipStream.Write(buffer, 0, size);
        try
        {
            while (size < streamToZip.Length)
            {
                int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
                zipStream.Write(buffer, 0, sizeRead);
                size += sizeRead;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        zipStream.Finish();
        zipStream.Close();
        streamToZip.Close();
    }



    private void ZipFolder(string source, string targetFile)
    {
        GetAllDirectories(source);
        while (source.LastIndexOf("\\") + 1 == source.Length)//check if the path endwith "\\"
        {
            source = source.Substring(0, source.Length - 1);//remove "\\"
        }
        string rootMark = source.Substring(0, source.LastIndexOf("\\") + 1);
        Crc32 crc = new Crc32();
        ZipOutputStream outPutStream = new ZipOutputStream(File.Create(targetFile));
        outPutStream.SetLevel(9); // 0 - store only to 9 - means best compression
        foreach (string file in files)
        {
            FileStream fileStream = File.OpenRead(file);
            byte[] buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, buffer.Length);
            ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));
            entry.DateTime = DateTime.Now;
            // set Size and the crc, because the information
            // about the size and crc should be stored in the header
            // if it is not set it is automatically written in the footer.
            // (in this case size == crc == -1 in the header)
            // Some ZIP programs have problems with zip files that don't store
            // the size and crc in the header.
            entry.Size = fileStream.Length;
            fileStream.Close();
            crc.Reset();
            crc.Update(buffer);
            entry.Crc = crc.Value;
            outPutStream.PutNextEntry(entry);
            outPutStream.Write(buffer, 0, buffer.Length);
        }
        this.files.Clear();
        foreach (string emptyPath in emptyFolders)
        {
            ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "\\");
            outPutStream.PutNextEntry(entry);
        }
        this.emptyFolders.Clear();
        outPutStream.Finish();
        outPutStream.Close();
    }

    private void GetAllDirectories(string rootPath)
    {
        string[] subPaths = Directory.GetDirectories(rootPath);
        foreach (string path in subPaths)
        {
            GetAllDirectories(path);
        }
        string[] filesArray = Directory.GetFiles(rootPath);
        foreach (string file in filesArray)
        {
            this.files.Add(file); //put all files in current folder into list
        }
        if (subPaths.Length == filesArray.Length && filesArray.Length == 0) //if it is an empty folder
        {
            this.emptyFolders.Add(rootPath);//add it to the list
        }
    }


    public class FileToZipArgument
    {
        public string FileName { get; set; }
        public byte[] FileContent { get; set; }
    }
}
